# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------------------
    File Name:  dict_demo
    Author   :  wanwei1029
    Date     :  2018-10-18
    Desc     :
------------------------------------------------------------------------------
"""
from collections import defaultdict

def exchange_key_value():
    """
    互换key和value
    :return:
    """
    a = {'aa': 11, 'bb': 22, 'cc': 33, 'a': 99}
    b = {value: key for key, value in a.items()}
    print(b)
    c = dict(zip(a.values(), a.keys()))
    print(c)


def combine_dicts():
    """
    合并两个字典，常用用**或update方法。
    :return:
    """
    a = {'a': 1, 'b': 2, 'c': 3}
    b = {'aa': 11, 'bb': 22, 'cc': 33, 'a': 99}
    # 如果有重复的元素，b的元素会替换a的元素
    c = dict(a, **b)
    print(c)
    d = dict()
    d.update(b)
    d.update(a)
    print(d)


def defaultdict_demo():
    """
    defaultdict 对于读取默认不存在的key，会返回一个空值，但是好像dict()也不会报错，也会返回None
    :return:
    """
    int_default = defaultdict(int)
    print(int_default.get("test"))

def intervalues_demo():
    """
    dict有values和intervalues两种方法获取所有values，不同的是，values是转换成一个List,但intervalues则不会。
    :return:
    """
    dict_obj = {"01": 1, "02": 5, "03": 2, "04": 4, "05": 1, "06": 7, "07": 5, "08": 1}
    # sum_obj = sum(intervalues(dict_obj))

def demo():
    """
    """
    dict_obj = {"01": 1, "02": 5, "03": 2, "04": 4, "05": 1, "06": 7, "07": 5, "08": 1}
    # dict_obj.items() 返回一个元组列表，item就是其中每一个key,value组成的元组
    # 注意，一定要是dict_obj.items,如果直接循环dict_obj，只会得到一个key的set.
    for item in dict_obj.items():
        print(item)
    # 要删除dict里的元素，要用del
    del dict_obj["01"]
    # 直接迭代dict对象，返回的是key值,和keys差不多
    for key in dict_obj:
        print(key)
    for key in dict_obj.keys():
        print(key)
    # 也可以迭代value值
    for value in dict_obj.values():
        print(value)
    # pop 操作
    pop_value = dict_obj.pop("02")
    print("pop="+str(pop_value))
    # 也可以用key，value分别把值取出来
    for key, value in dict_obj.items():
        print(key+"="+str(value))
    key_05 = "05"
    key_value = dict_obj.get(key_05)
    print("get value :{0}".format(key_value))


if __name__ == '__main__':
    test_method = "demo"
    if test_method == "demo":
        demo()
    elif test_method == "combine_dicts":
        combine_dicts()
    elif test_method == "exchange_key_value":
        exchange_key_value()
    elif test_method == "defaultdict_demo":
        defaultdict_demo()

